package nc.ui.ep.dj;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import nc.bs.logging.Log;
import nc.cmp.pub.cache.FiPubDataCache;
import nc.ui.arap.actions.AddAction;
import nc.ui.arap.actions.CopyDjAction;
import nc.ui.arap.actions.SearchAction;
import nc.ui.arap.actions.SearchActionNor;
import nc.ui.arap.buttonstat.DjCopyBtnStatLisener;
import nc.ui.arap.buttonstat.StatListenerHelper;
import nc.ui.arap.engine.ExtBtnProxy;
import nc.ui.arap.engine.ExtButtonObject;
import nc.ui.arap.global.DjTempletHelper;
import nc.ui.arap.pubdj.ArapDjPanel;
import nc.ui.cmp.ISettlementPanel;
import nc.ui.pub.ButtonObject;
import nc.ui.pub.pf.PfUtilClient;
import nc.vo.arap.djlx.DjLXVO;
import nc.vo.arap.exception.ExceptionHandler;
import nc.vo.arap.global.ArapDjCalculator;
import nc.vo.arap.global.DjVOTreaterAid;
import nc.vo.ep.dj.DJZBHeaderVO;
import nc.vo.ep.dj.DJZBItemVO;
import nc.vo.ep.dj.DJZBVO;
import nc.vo.ep.dj.DJZBVOConsts;
import nc.vo.ml.AbstractNCLangRes;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;

public abstract class FiFlowPanel extends ArapBaseEntry {
	DjCopyBtnStatLisener cpyListener = null;

	CopyDjAction cpy = new CopyDjAction();

	ButtonObject[] btns;

	protected List<String> outflow = Arrays.asList(new String[] { "FZ", "45",
			"Z4", "Z5", "50", "21", "33", "25", "4501", "Z2", "4453", "5HZG",
			"4814", "4816", "4T", "5F", "5GZG", "4812", "30" });

	public FiFlowPanel() {
		this.cpyListener = new DjCopyBtnStatLisener();
		this.cpyListener.setActionRunntimeV0(this);
		this.cpy.setActionRunntimeV0(this);
	}

	public FiFlowPanel(int syscode) {
		super(syscode);
		this.cpyListener = new DjCopyBtnStatLisener();
		this.cpyListener.setActionRunntimeV0(this);
		this.cpy.setActionRunntimeV0(this);
	}

	public ButtonObject[] getDjButtons() {
		ButtonObject[] ret = null;
		if ((getLastWorkPage() == getCurrWorkPage()) && (this.btns != null)) {
			return this.btns;
		}

		if (getArapDjPanel1().isSelectSettleTab())
			this.btns = getArapDjPanel1().getSettlePanel().getButtons();
		else {
			try {
				ret = (getExtBtnProxy().getButtons() == null) ? new ButtonObject[0]
						: getExtBtnProxy().getButtons();
				if (ArapBillWorkPageConst.CARDPAGE == getCurrWorkPage()) {
					ButtonObject[] localArray = null;
					if (getPanelProp() == 0) {
						localArray = new ButtonObject[] { this.m_boAdd,
								this.m_boCpy };
					}
					this.btns = new ButtonObject[((ret == null) ? 0
							: ret.length)
							+ ((localArray == null) ? 0 : localArray.length)];
					if ((null != localArray) && (localArray.length > 0))
						System.arraycopy(localArray, 0, this.btns, 0,
								localArray.length);
					if ((null != ret) && (ret.length > 0))
						System.arraycopy(ret, 0, this.btns,
								(localArray == null) ? 0 : localArray.length,
								ret.length);
				} else {
					this.btns = ret;
				}
			} catch (Exception e) {
				Log.getInstance(super.getClass()).error(e);
				showErrorMessage(e.getMessage());

				showHintMessage(e.getMessage());
			}
		}

		return this.btns;
	}

	public void onButtonClicked(ButtonObject bo) {
		beginPressBtn(bo);
		showProgressBar(true);
		String butitype = null;
		if (bo.getParent() == this.m_boAdd) {
			if (!checkID())
				return;
			try {
				butitype = selectBusitype(bo);
			} catch (BusinessException e1) {
				showProgressBar(false);
				return;
			}
			PfUtilClient.childButtonClicked(bo, getCurrentCorp(),
					getNodeCode(), getDjSettingParam().getPk_user(),
					getDjDataBuffer().getCurrentDjlxbm(), this);

			if (PfUtilClient.makeFlag) {
				AddAction add = new AddAction();
				add.setActionRunntimeV0(this);
				try {
					add
							.add(bo.getTag().substring(
									1 + bo.getTag().indexOf(":")));
				} catch (Exception e) {
					showErrorMessage(e.getMessage());
					showHintMessage(e.getMessage());
				}
			} else if (PfUtilClient.isCloseOK()) {
				AggregatedValueObject[] vos = PfUtilClient.getRetVos();

				for (AggregatedValueObject vo : vos) {
					DJZBVO djvo = (DJZBVO) vo;
					DJZBItemVO[] items = djvo.items;
					DJZBHeaderVO head = djvo.header;
					for (DJZBItemVO item : items) {
						try {
							ArapDjCalculator.getInstance().changeBodyByYbje(
									item, djvo.header);
							item = ArapDjCalculator.getInstance().calculateVO(
									item,
									"bzbm",
									getDjSettingParam().getLoginDate()
											.toString(),
									head.getDjdl(),
									ArapDjCalculator.getInstance().getProior(
											head));
						} catch (NullPointerException e) {
							ExceptionHandler.consume(e);
						} catch (Exception e) {
							ExceptionHandler.consume(e);
							showErrorMessage(e.getMessage());
						}
					}
					DjVOTreaterAid.sumBtoH(djvo);
				}

				resetBillMap(vos);
				try {
					showbills(vos, butitype);
				} catch (Exception e) {
					showErrorMessage(e.getMessage());
				}
			}
		} else if (bo.getParent() == this.m_boCpy) {
			if (!checkID())
				return;
			try {
				butitype = bo.getTag().substring(bo.getTag().indexOf(":") + 1);

				this.cpy.copyDj(butitype);
			} catch (Exception e1) {
				showErrorMessage(e1.getMessage());
				showProgressBar(false);
				return;
			}
		} else {
			super.onButtonClicked(bo);
		}

		if (isSuccess()) {
			endPressBtn(bo);
		}
		cpyAndAddBoStatListener();
		showProgressBar(false);
		updateButtonStatus();
	}

	public void cpyAndAddBoStatListener() {
		if (("200602".equals(getDjSettingParam().getNodeID()))
				|| ("200802".equals(getDjSettingParam().getNodeID()))) {
			if ((StatListenerHelper.getQcIsClose(this))
					|| (StatListenerHelper.checkQcdj_jzxx(this))) {
				this.m_boCpy.setEnabled(false);
				this.m_boAdd.setEnabled(false);
			} else {
				if (null != getDjDataBuffer().getCurrentDJZBVO())
					this.m_boCpy.setEnabled(true);
				else {
					this.m_boCpy.setEnabled(false);
				}
				this.m_boAdd.setEnabled(true);
			}
		} else if (DjTempletHelper.isCardInEdit(this)) {
			this.m_boCpy.setEnabled(false);
			this.m_boAdd.setEnabled(false);
		} else {
			if (null != getDjDataBuffer().getCurrentDJZBVO())
				this.m_boCpy.setEnabled(true);
			else {
				this.m_boCpy.setEnabled(false);
			}
			this.m_boAdd.setEnabled(true);
		}
	}

	private void resetBillMap(AggregatedValueObject[] vos) {
		Map map = new HashMap();
		for (AggregatedValueObject agvo : vos) {
			DJZBVO vo = (DJZBVO) agvo;
			DJZBItemVO[] items = vo.items;
			for (DJZBItemVO item : items) {
				if ((item.getBillmap() != null)
						&& (item.getBillmap().size() != 0)) {
					map.put(item.getFb_oid(), item.getBillmap());
				}
			}
		}
		if (map.size() != 0)
			setAttribute("FlowMap", map);
	}

	public void updateLocalButtons() throws Exception {
		if (null == getDjDataBuffer().getCurrentDjdl())
			return;
		PfUtilClient.retAddBtn2(this.m_boAdd, getCurrentCorp(),
				getBilltype(getDjDataBuffer().getCurrentDjdl()),
				getDjDataBuffer().getCurrentDjlxbm());

		PfUtilClient.retCopyBtn(this.m_boCpy, getCurrentCorp(),
				getBilltype(getDjDataBuffer().getCurrentDjdl()),
				getDjDataBuffer().getCurrentDjlxbm());

		List btns = new ArrayList();
		int i = 0;
		for (int size = this.m_boAdd.getChildCount(); i < size; ++i) {
			if (getDjSettingParam().getIsQc()) {
				if (this.m_boAdd.getChildButtonGroup()[i].getTag().startsWith(
						"makeflag:")) {
					btns.add(this.m_boAdd.getChildButtonGroup()[i]);
				}
			} else
				btns.add(this.m_boAdd.getChildButtonGroup()[i]);
			this.m_boAdd.getChildButtonGroup()[i].setPowerContrl(false);
		}
		this.m_boAdd.setChildButtonGroup((ButtonObject[]) btns
				.toArray(new ButtonObject[0]));
		btns.clear();

		 i = 0;
		for (int size = this.m_boCpy.getChildCount(); i < size; ++i) {
			if (getDjSettingParam().getIsQc()) {
				if (this.m_boCpy.getChildButtonGroup()[i].getTag().startsWith(
						"makeflag:")) {
					btns.add(this.m_boCpy.getChildButtonGroup()[i]);
				}
			} else
				btns.add(this.m_boCpy.getChildButtonGroup()[i]);
			this.m_boCpy.getChildButtonGroup()[i].setPowerContrl(false);
		}
		this.m_boCpy.setChildButtonGroup((ButtonObject[]) btns
				.toArray(new ButtonObject[0]));
		setButtons(getDjButtons());
	}

	protected void showbills(AggregatedValueObject[] vos, String busitype)
			throws Exception {
		getDjDataBuffer().getListSelectedVOs().clear();
		int pzglh = getDjSettingParam().getSyscode();
		settlevo(vos, pzglh, busitype);
		SearchAction sa = new SearchActionNor();
		sa.setActionRunntimeV0(this);
		SearchActionNor san = new SearchActionNor();
		san.setActionRunntimeV0(this);
		san.changeTab();
		sa.updateListPanel((DJZBVO[]) (DJZBVO[]) vos);

		getDjDataBuffer().setCurrentDJZBVO((DJZBVO) vos[0]);
	}

	protected void settlevo(AggregatedValueObject[] vos, int pzglh,
			String busitype) throws Exception {
		int pos = 0;
		int i = 0;
		for (int size = vos.length; i < size; ++i) {
			DJZBHeaderVO head = (DJZBHeaderVO) vos[i].getParentVO();
			head.setVouchid(DJZBVOConsts.ARAP_TEMP_VOUCHID + pos++);
			head.setDjzt(Integer.valueOf(-100));
			head.setTransientFlag(DJZBVOConsts.ACT_FLOW_BILL);
			if (null != busitype) {
				head.setXslxbm(busitype);
			}
			if (pzglh != head.getPzglh().intValue()) {
				head.setPzglh(Integer.valueOf(pzglh));
			}
			if (getDjSettingParam().getIsQc()) {
				head.setQcbz(UFBoolean.TRUE);
				try {
					UFDate qyrq = getDjSettingParam().getQyrq2();

					head.setDjrq(qyrq.getDateBefore(1));
					head.setEffectdate(qyrq.getDateBefore(1));
				} catch (Throwable e) {
				}
				head.setShrq(getDjSettingParam().getLoginDate());
				head.setDjzt(Integer.valueOf(2));
			}
		}
	}

	protected String getBilltype(String djdl) {
		String billtype = null;
		if ("ys".equals(djdl))
			billtype = "F0";
		else if ("yf".equals(djdl))
			billtype = "F1";
		else if ("sk".equals(djdl))
			billtype = "F2";
		else if ("fk".equals(djdl))
			billtype = "F3";
		else if ("sj".equals(djdl))
			billtype = "F4";
		else if ("fj".equals(djdl))
			billtype = "F5";
		else if ("hj".equals(djdl))
			billtype = "F6";
		return billtype;
	}

	protected String selectBusitype(ButtonObject bt) throws BusinessException {
		if ((null == bt) || (bt.getTag() == null))
			return null;

		String billtype = bt.getTag().substring(0, bt.getTag().indexOf(":"));
		if (!isOutFlowBillType(billtype)) {
			return null;
		}
		List busi = new ArrayList();
		StringTokenizer st = new StringTokenizer(bt.getTag().substring(
				bt.getTag().indexOf(":") + 1), ",");
		while (st.hasMoreElements()) {
			busi.add((String) st.nextElement());
		}
		if (busi.size() == 1)
			return (String) busi.get(0);
		ArapBusiConfirmDLg dlg = new ArapBusiConfirmDLg(this);
		dlg.showModel((String[]) busi.toArray(new String[0]));
		if (dlg.isOK()) {
			return dlg.getSelectData();
		}
		throw ExceptionHandler.createException(NCLangRes4VoTransl
				.getNCLangRes().getStrByID("businessbill",
						"UPPbusinessbill-000087"));
	}

	protected boolean isOutFlowBillType(String billtype) {
		if (this.outflow.contains(billtype))
			return true;
		DjLXVO djlxvo = FiPubDataCache.getBillType(billtype,
				getCorpPrimaryKey());

		return (null != djlxvo) && ("ss".equals(djlxvo.getDjdl()));
	}

}